<template>
  <div class="page-auto-complete" :title="readonly ? autoValue : ''">
    <Input
      :disabled="readonly"
      v-model.trim="autoValue"
      :placeholder="placeholder ? placeholder : '请选择'"
      @on-focus="focusHandler"
      @on-blur="blurHandler"
      @on-change="changeHandler"
    />

    <div class="ivu-select-dropdown" ref="selectDrop" v-show="showAutoDatas && dataSource.length>0">
      <ul class="ivu-select-dropdown-list">
        <li
          :class="['ivu-select-item',{'ivu-select-item-focus':activeIndex === index}]"
          :title="item"
          v-for="(item,index) of dataSource"
          :key="index"
          @click.stop="selectAuto(item)"
        >{{item}}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
export default {
  props: ['value', 'placeholder', 'readonly'],
  data () {
    return {
      autoValue: '',
      showAutoDatas: false,
      dataSource: [],
      selectClick: false,
      activeIndex: null
    };
  },
  computed: {
    ...mapState({
      autoDatas: state => state.workflow.autoDatas
    })
  },
  methods: {
    ...mapMutations(['setAutoDatas']),

    // 输入
    changeHandler () {
      // 过滤匹配
      let arr = [];
      this.autoDatas.forEach(item => {
        if (item.includes(this.autoValue)) {
          arr.push(item);
        }
      });

      this.dataSource = arr;
      this.showAutoDatas = arr.length > 0;
      if (!this.showAutoDatas) {
        this.activeIndex = null;
      }
    },

    // 触发焦点
    focusHandler (e) {
      if (!this.autoValue) {
        this.changeHandler();
      }
    },

    // 失去焦点
    blurHandler (e) {
      setTimeout(() => {
        if (this.selectClick) {
          this.selectClick = false;
          return;
        }
        this.$emit('autoBlur', this.autoValue);
        if (this.autoValue && this.autoValue.length > 2) {
          this.setAutoDatas(this.autoValue);
        }
      }, 200);
    },

    clickHandler (e) {
      // e.stopPropagation();
      // e.preventDefault();
      if (e.target.nodeName !== 'INPUT') {
        this.showAutoDatas = false;
        this.activeIndex = null;
      }
    },

    keyUpHandler (e) {
      e.preventDefault();
      const keyCode = e.keyCode || e.which;
      const len = this.dataSource.length;

      // 向下按
      if (keyCode === 40 && this.showAutoDatas && this.dataSource.length > 0) {
        this.activeIndex =
          this.activeIndex === null || this.activeIndex + 1 === len
            ? 0
            : this.activeIndex + 1;
      }

      // 向下按
      if (keyCode === 38 && this.showAutoDatas && this.dataSource.length > 0) {
        this.activeIndex =
          this.activeIndex === 0 ? len - 1 : this.activeIndex - 1;
      }

      // 滚动条
      if (len > 7) {
        let currentItem =
          this.$refs.selectDrop &&
          this.$refs.selectDrop.querySelector('.ivu-select-item-focus');

        if (currentItem) {
          if (this.activeIndex === 0) {
            this.$refs.selectDrop.scrollTop = 0;
          } else {
            this.$refs.selectDrop.scrollTop =
              (Math.ceil((this.activeIndex + 1) / 7) - 1) * 200;
          }
        }
      }

      // enter确定
      if (
        keyCode === 13 &&
        this.showAutoDatas &&
        this.dataSource.length > 0 &&
        this.activeIndex !== null
      ) {
        this.selectAuto(this.dataSource[this.activeIndex]);
      }
    },

    // 选择自动补全的数据
    selectAuto (item) {
      this.selectClick = true;
      this.autoValue = item;
      this.showAutoDatas = false;
      this.activeIndex = null;
      this.$emit('autoBlur', this.autoValue);
    }
  },
  mounted () {
    if (this.value) {
      this.autoValue = this.value;
    }

    document.addEventListener('click', this.clickHandler);
    document.addEventListener('keyup', this.keyUpHandler);
  },

  destroyed () {
    document.removeEventListener('click', this.clickHandler);
    document.addEventListener('keyup', this.keyUpHandler);
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.page-auto-complete {
  display: inline-block;
  width: 100%;
  position: relative;
  .ivu-select-dropdown{
    width: 100%;
  }
  .ivu-select-dropdown-list {
    overflow-x: hidden;
    .ivu-select-item {
      max-width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
</style>
